//
//  WBOauthViewController.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/4.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit
import SVProgressHUD
class WBOauthViewController: UIViewController,UIWebViewDelegate {
    
    //定义一个WebView
    let webView: UIWebView = UIWebView()
    
    override func loadView() {
        view = webView
        //添加导航栏
        setupNav()
    }
    
    //定义登录WEbview的导航栏
    func setupNav() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autofill")
    }
    
    
    //MARK:-- Nav的点击方法
    //定义为私有方法要加 @objc
    @objc private func dismiss() {
        //返回点击方法
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    //自动填充方法
    @objc private func autofill() {
        let js = "document.getElementById(\"userId\").value = \"xiaoziyong1008\";document.getElementById(\"passwd\").value = \"xiaoziyong\""
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //18692052752
        //W19911125
        //document.getElementById("passwd").value = "xiaoziyong"
        //document.getElementById("userId").value = "xiaoziyong1008"
        //https://api.weibo.com/oauth2/authorize?client_id=718015919&redirect_uri=http://www.devshaw.com
        
        //1. 创建url
        let urlstring = "https://api.weibo.com/oauth2/authorize?client_id=718015919&redirect_uri=http://www.devshaw.com"
        
        //2. 创建一个NSURL
        let url = NSURL(string: urlstring)!
        //3.创建requet
        let requst = NSURLRequest(URL: url)
        //4.页面加载
        webView.loadRequest(requst)
        //设置webView的代理方法
        webView.delegate = self
    }
}

// MARK:--UIWebViewDelegate 代理方法
extension WBOauthViewController {
    //已经开始加载的方法
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD .show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    //加载出现的错误
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        // SVProgressHUD .showErrorWithStatus("加载错误")
    }
    
    //每次加载都会调用 从这里来获取
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //printLog(request.URL)
        
        if  let absolueString = request.URL?.absoluteString {
            if absolueString.hasPrefix(AppRedictUrl) {
                //  printLog("输出加载URL:\(absolueString)")
                // http://www.devshaw.com/?code=8c4838cb0ba8895f7f7967005f53112a
                //获取code
                if let query = request.URL?.query{
                    //字符串截取
                    let code = query.substringFromIndex("code=".endIndex)
                    
                    //printLog("code:\(code)")
                    
                    
                    //调用AFN的请求来换取Token
                    WBOauthViewModel.shareInstance.loadToken(code, suess: { () -> () in
                        //请求成功让视图消失
                        self.dismiss()
                        //MARK:发送通知 切换
                        NSNotificationCenter.defaultCenter().postNotificationName(kNotificationChangeViewControler, object: self)
                        
                        }, failed: { () -> () in
                            //在此处理错误信息
                    })
                }
                
                return false
            }
        }
        
        return true
    }
}


